// wavcut.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <iterator>

#define NUMBER_OF_ELEMENTS_IN(_x) (sizeof(_x)/sizeof(_x[0]))

static int usage()
{
	static const char* text[] =
	{ "Perlin Production Co.Ltd. June 2014"
	, "cuts RIFF header, writes 2 high bits of 16-bit sample"
	, "usage: wavcut infile[.wav]"
	};
	std::copy	( &text[0]
				, &text[NUMBER_OF_ELEMENTS_IN(text)]
				, std::ostream_iterator<const char*>(std::cout,"\n")
				);
	return -1;
}

static int FailedTo( const char* _text1
			, const char* _text2
			)
{
	std::cout << "Failed to " << _text1 << " " << _text2;
	return -2;
}

enum SoundModuleFormat
{	SMF_NUL		//EQU	0	; NUL (no) sound
,	SMF_DAC		//EQU	1	; Analog to Digital Conversion
,	SMF_STM		//EQU	2	; Sound Tracker Module
,	SMF_TFS		//EQU	3	; Timer Sequence of Frequences
,	SMF_PWM		//EQU	4	; Pulse-width Modulation
};

static const unsigned char hdrSnd[]=
{ 'S'
, 'N'
, 'D'
, 0x1		//header version
, SMF_DAC	//Sound Module Format (see SNDDRV.INC)
//------ This is passed to sound driver to play -------
, 3			//suggested memory bank
, 0
, 0			// suggested base address in memory
, 0x00
, 0xF4		//size
, 0xFF		//channel id, 0xFF - any
, 0			//speed parameter (delay)
, 0,0,0,0	//reserved for future extensions
};

int main(int _argc, const char* _argv[])
{
	if (_argc != 2) return usage();
	std::ifstream input(_argv[1],std::ios::binary);
	if (!input.is_open()) return FailedTo("open",_argv[1]);	//std::cout << input.rdbuf();
	static const char* outfilename = "electric.cd2";
	std::ofstream	output( outfilename, std::ios::out | std::ios::trunc | std::ios::binary);
	if (!output.is_open()) return FailedTo("create",outfilename);

	std::copy	( &hdrSnd[0]
				, &hdrSnd[NUMBER_OF_ELEMENTS_IN(hdrSnd)]
				, std::ostream_iterator<unsigned char>(output)
				);
	input.seekg(44);	//RIFF header size
	char x[4];
	while(!input.read(x,4).eof())
	{
		register char c = 0;
		for (int i=0; i < NUMBER_OF_ELEMENTS_IN(x); ++i)
		{
			c |= ((x[i] & 0xC0) >> (6-2*i));
			//output.put(x[i]);
		}
		output.put(c);
	}
	output.close();

	return 0;
}
